package com.jianyun.jyzs.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.hannesdorfmann.mosby3.mvp.MvpActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.Sign;
import com.jianyun.jyzs.bean.SignResult;
import com.jianyun.jyzs.dao.SignDao;
import com.jianyun.jyzs.presenter.SginPresenter;
import com.jianyun.jyzs.utils.DeviceUtils;
import com.jianyun.jyzs.utils.LocationManager;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.NetUtil;
import com.jianyun.jyzs.utils.TimeUtils;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.view.iview.ISignView;
import com.jrmf360.rylib.common.util.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import com.jianyun.jyzs.utils.RceLog;

/**
 * 签到界面
 * Created by yangshijun on 2018/5/30.
 */

public class SigninActivity extends MvpActivity<ISignView, SginPresenter> implements ISignView
        , GeocodeSearch.OnGeocodeSearchListener {


    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.tv_checked)
    TextView tvChecked;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_moreLinearLayout)
    LinearLayout ivMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.iv_single)
    ImageView ivSingle;
    @BindView(R.id.iv_group)
    ImageView ivGroup;
    @BindView(R.id.topChatDetail)
    LinearLayout topChatDetail;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.ic_datetime2)
    ImageView icDatetime2;
    @BindView(R.id.tv_currentTime)
    TextView tvCurrentTime;
    @BindView(R.id.tv_mdate)
    TextView tvMdate;
    @BindView(R.id.tv_mstate)
    TextView tvMstate;
    @BindView(R.id.tv_maddr)
    TextView tvMaddr;
    @BindView(R.id.tv_adate)
    TextView tvAdate;
    @BindView(R.id.tv_astate)
    TextView tvAstate;
    @BindView(R.id.tv_aaddr)
    TextView tvAaddr;
    @BindView(R.id.tv_mapBtn)
    TextView tvMapBtn;
    @BindView(R.id.iv_anim11)
    ImageView ivAnim11;
    @BindView(R.id.iv_anim1)
    ImageView ivAnim1;
    @BindView(R.id.iv_anim2)
    ImageView ivAnim2;
    @BindView(R.id.iv_anim22)
    ImageView ivAnim22;
    @BindView(R.id.iv_anim3)
    ImageView ivAnim3;
    @BindView(R.id.iv_anim33)
    ImageView ivAnim33;
    @BindView(R.id.iv_anim4)
    ImageView ivAnim4;
    @BindView(R.id.iv_anim44)
    ImageView ivAnim44;
    @BindView(R.id.tv_signBtn)
    TextView tvSignBtn;


    private String[] NETTYPE = {"定位失败", "GPRS", "前次定位结果", "缓存定位结果", "Wifi", "EDGE", "离线定位结果"};//网络类型
    private String userId;
    private String enterpriseCode;
    private String label = "";
    private ProgressDialog dialog;
    private LocationManager locationManager;
    private static AMapLocation aMapLocation;
    private GeocodeSearch geocoderSearch;
    private boolean isAginSign = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this, true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_signin);
        ButterKnife.bind(this);
        initData();
        initView();
        initAnim();
        initSignTime();
    }

    private void initData() {
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        dialog = new ProgressDialog(this);
        dialog.setMessage("loading...");
        locationManager = new LocationManager(this);
    }

    private void initView() {
        //hintActionBar(true);
        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(this);
        topBack.setVisibility(View.VISIBLE);
        topText.setText("签到");
        tvCurrentTime.setText(TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd")) + " " + TimeUtils.getWeekOfDate());
        ivMoreLinearLayout.setVisibility(View.VISIBLE);
        ivMore.setVisibility(View.VISIBLE);
        ivMore.setImageResource(R.drawable.create_order_calendar);
    }

    private void initAnim() {
        //使用AnimationUtils类的静态方法loadAnimation()来加载XML中的动画XML文件
        Animation animation11 = AnimationUtils.loadAnimation(this, R.anim.sign_translate11);
        ivAnim11.startAnimation(animation11);
        Animation animation22 = AnimationUtils.loadAnimation(this, R.anim.sign_translate22);
        ivAnim22.startAnimation(animation22);
        Animation animation33 = AnimationUtils.loadAnimation(this, R.anim.sign_translate33);
        ivAnim33.startAnimation(animation33);
        Animation animation44 = AnimationUtils.loadAnimation(this, R.anim.sign_translate44);
        ivAnim44.startAnimation(animation44);
        Animation animation1 = AnimationUtils.loadAnimation(this, R.anim.sign_translate1);
        ivAnim1.startAnimation(animation1);
        Animation animation2 = AnimationUtils.loadAnimation(this, R.anim.sign_translate2);
        ivAnim2.startAnimation(animation2);
        Animation animation3 = AnimationUtils.loadAnimation(this, R.anim.sign_translate3);
        ivAnim3.startAnimation(animation3);
        Animation animation4 = AnimationUtils.loadAnimation(this, R.anim.sign_translate4);
        ivAnim4.startAnimation(animation4);
    }

    @NonNull
    @Override
    public SginPresenter createPresenter() {
        return new SginPresenter();
    }

    @OnClick({R.id.topBack, R.id.iv_moreLinearLayout, R.id.tv_mapBtn, R.id.tv_signBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.topBack:
                finish();
                break;
            case R.id.iv_moreLinearLayout:
                startActivity(new Intent(this, SignCalendarActivity.class));
                break;
            case R.id.tv_mapBtn:
                startActivity(new Intent(this, SignMapActivity.class));
                break;
            case R.id.tv_signBtn:
                locationManager.locationStart(dialog, new LocationManager.LocationManagerListener() {
                    @Override
                    public void locationResult(boolean result, AMapLocation aMapLocation) {
                        if (result) {
                            SigninActivity.aMapLocation = aMapLocation;
                            dialog.setMessage("定位成功");
                            String adress = aMapLocation.getCountry() + aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getStreet();
                            if (null == adress || TextUtils.isEmpty(adress)) {
                                //先逆获取地址编码
                                LatLonPoint latLonPoint = new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                                // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
                                RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
                                geocoderSearch.getFromLocationAsyn(query);
                                isAginSign = true;
                            } else {
                                //打卡
                                signIn(aMapLocation, adress);
                            }
                        } else {
                            dialog.dismiss();
                            dialog.setMessage("定位失败" + aMapLocation.getErrorCode());
                        }
                    }
                });
                break;
        }
    }

    //签到
    private void signIn(AMapLocation aMapLocation, String adress) {
        Log.i("test", "逆转录地址：" + adress);
        HashMap<String, String> map = new HashMap<>();
        map.put("method", "Sign");
        map.put("enterpriseCode", enterpriseCode);
        map.put("employeeId", userId);
        double[] gaoDeToBaidu = gaoDeToBaidu(aMapLocation.getLongitude(), aMapLocation.getLatitude());
        String LOCATION_Y = gaoDeToBaidu[0] + "";
        String LOCATION_X = gaoDeToBaidu[1] + "";
        map.put("location_X", LOCATION_X);
        map.put("location_Y", LOCATION_Y);
        map.put("scale", "5");
        map.put("label", adress);
        String deviceId = DeviceUtils.getAndroidID(this);
        map.put("deviceId", deviceId);
        map.put("netType", NETTYPE[aMapLocation.getLocationType()]);
        map.put("platFormInfo", "android");
        map.put("userIp", NetUtil.getLocalIpAddress());
        map.put("sourceSystem", "jyzs");
        label = adress;
        if (null == label || TextUtils.isEmpty(label)) {
            //先逆获取地址编码
            LatLonPoint latLonPoint = new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
            RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
            geocoderSearch.getFromLocationAsyn(query);
            isAginSign = false;
        }
        Log.i("test", "地址：" + label);
        //签到
        getPresenter().startSign(map);

    }


    public static double[] gaoDeToBaidu(double gd_lon, double gd_lat) {
        double[] bd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = gd_lon, y = gd_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
        bd_lat_lon[0] = z * Math.cos(theta) + 0.0065;
        bd_lat_lon[1] = z * Math.sin(theta) + 0.006;
        return bd_lat_lon;
    }

    private void initSignTime() {

        //处理上午时间
        Sign po = new SignDao(this).getStartDate(userId, TimeUtils.getNowStringDate("yyyy_MM_dd"), enterpriseCode);
        RceLog.d("lml", "处理上午时间 TimeUtils.getNowStringDate(yyyy_MM_dd)=" + TimeUtils.getNowStringDate("yyyy_MM_dd"));
        if (po != null) {
            tvMdate.setText(po.getDateTime().substring(11, 16).replaceAll(":", " : "));//上午时间
            tvMaddr.setText(po.getAddress());//上午签到地点
            if (po.getMorningPlaceValid() != null && po.getMorningPlaceValid().equals("1")) {
                tvMaddr.setTextColor(tvMdate.getResources().getColor(R.color.red));
            } else {
                tvMaddr.setTextColor(tvAdate.getResources().getColor(R.color.sign_addr));
            }
            if (po.getMorningTimeValid() != null && po.getMorningTimeValid().equals("1")) {
                tvMstate.setVisibility(View.VISIBLE);//上午签到状态
                tvMdate.setTextColor(tvMdate.getResources().getColor(R.color.red));
            } else {
                tvMstate.setVisibility(View.GONE);//下午签到状态
                tvMdate.setTextColor(tvMdate.getResources().getColor(R.color.black));
            }
        }
        //处理下午时间
        po = new SignDao(this).getEndDate(userId, TimeUtils.getNowStringDate("yyyy_MM_dd"), enterpriseCode);
        if (po != null) {//下午
            tvAdate.setText(po.getDateTime().substring(11, 16).replaceAll(":", " : "));//下午时间
            tvAaddr.setText(po.getAddress());//下午签到地点
            if (po.getAfternoonPlaceValid() != null && po.getAfternoonPlaceValid().equals("1")) {
                tvAaddr.setTextColor(tvAdate.getResources().getColor(R.color.red));
            } else {
                tvAaddr.setTextColor(tvAdate.getResources().getColor(R.color.sign_addr));
            }
            if (po.getAfternoonTimeValid() != null && po.getAfternoonTimeValid().equals("1")) {
                tvAstate.setVisibility(View.VISIBLE);//下午签到状态
                tvAdate.setTextColor(tvAdate.getResources().getColor(R.color.red));
            } else {
                tvAstate.setVisibility(View.GONE);//下午签到状态
                tvAdate.setTextColor(tvAdate.getResources().getColor(R.color.black));
            }
        }
    }

    @Override
    public void onSignSuccess(SignResult signResult) {
        isAginSign = false;
        if (label == null || TextUtils.isEmpty(label)) {
            label = "";
        }
        // dialog.setMessage("签到完成" + signResult.getMessage());
        dialog.dismiss();
        String dateTime = null;
        List<SignResult.ReturnJsonBean> returnJson = signResult.getReturnJson();
        dateTime = signResult.getSignTime();
        if (TimeUtils.string2Millis(dateTime, TimeUtils.getFormat1()) != -1) {
            dateTime = TimeUtils.stringChange(dateTime);
        }
        if (TimeUtils.string2Millis(dateTime, TimeUtils.getFormat2()) != -1) {
            dateTime = TimeUtils.stringChange2(dateTime);
        }

        Sign po = new Sign(null, dateTime, userId, dateTime.substring(0, 10), label, enterpriseCode);
        po.setAfternoonPlaceValid(returnJson.get(0).getAfternoonPlaceValid());
        po.setAfternoonTimeValid(returnJson.get(0).getAfternoonTimeValid());
        po.setMorningPlaceValid(returnJson.get(0).getMorningPlaceValid());
        po.setMorningTimeValid(returnJson.get(0).getMorningTimeValid());
        new SignDao(this).insert(po, enterpriseCode);
        RceLog.d("lml", po.toString());
        initSignTime();
    }

    @Override
    public void onFailed(String msg) {
        ToastUtil.showNoWaitToast(this, msg);
    }

    @Override
    public void showLoading() {
        dialog.setMessage("开始签到");
    }

    @Override
    public void hintLoading() {
        dialog.dismiss();
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        if (i == 1000) {
            RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
            String formatAddress = regeocodeAddress.getFormatAddress();
            label = regeocodeAddress.getFormatAddress();
            if (isAginSign) {
                signIn(aMapLocation, formatAddress);
            }

        } else {
            if (isAginSign) {
                signIn(aMapLocation, "");
            }
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }
}
